import { Request, Response } from 'express';
import { parse } from 'url';
import { KConfigItem, TableListParams } from '@/pages/ConfigEdit/data';

let kConfigPrimarySource: KConfigItem[] = [
  {
    key: 1,
    confName:  'K_CONF_DB_HOST',
    confType: 1,
    createdAt: new Date(),
    user: 'laofa',
    instances: [
      {key: 100001, instance: 'f1', confName: 'K_CONF_DB_HOST', confValue: '10.110.0.13', updatedAt: new Date(), user: 'laofa'},
      {key: 100002, instance: 'f2', confName: 'K_CONF_DB_HOST', confValue: '10.110.0.14', updatedAt: new Date(), user: 'laofa'},
      {key: 100003, instance: 'f3', confName: 'K_CONF_DB_HOST', confValue: '10.110.0.10', updatedAt: new Date(), user: 'laofa'},
      {key: 100004, instance: 'f4', confName: 'K_CONF_DB_HOST', confValue: '10.110.1.23', updatedAt: new Date(), user: 'laofa'},
      {key: 100005, instance: 'uat', confName: 'K_CONF_DB_HOST', confValue: '10.110.2.45', updatedAt: new Date(), user: 'laofa'},
      {key: 100006, instance: 'release', confName: 'K_CONF_DB_HOST', confValue: '10.110.0.13', updatedAt: new Date(), user: 'laofa'},
    ],
  },
  {
    key: 2,
    confName:  'K_CONF_DB_PORT',
    confType: 1,
    createdAt: new Date(),
    user: 'laofa',
    instances: [
      {key: 200001, instance: 'f1', confName: 'K_CONF_DB_PORT', confValue: '5329', updatedAt: new Date(), user: 'laofa'},
      {key: 200002, instance: 'f2', confName: 'K_CONF_DB_PORT', confValue: '5329', updatedAt: new Date(), user: 'laofa'},
      {key: 200003, instance: 'f3', confName: 'K_CONF_DB_PORT', confValue: '5329', updatedAt: new Date(), user: 'laofa'},
      {key: 200004, instance: 'f4', confName: 'K_CONF_DB_PORT', confValue: '5329', updatedAt: new Date(), user: 'laofa'},
      {key: 200005, instance: 'uat', confName: 'K_CONF_DB_PORT', confValue: '5329', updatedAt: new Date(), user: 'laofa'},
      {key: 200006, instance: 'release', confName: 'K_CONF_DB_PORT', confValue: '5329', updatedAt: new Date(), user: 'laofa'},
    ],
  },
  {
    key: 3,
    confName: 'K_CONF_DB_NAME',
    confType: 1,
    createdAt: new Date(),
    user: 'laofa',
    instances: [
      {key: 300001, instance: 'f1', confName: 'K_CONF_DB_NAME', confValue: 'karbon_ss_v2', updatedAt: new Date(), user: 'laofa'},
      {key: 300002, instance: 'f2', confName: 'K_CONF_DB_NAME', confValue: 'karbon_ss_v2', updatedAt: new Date(), user: 'laofa'},
      {key: 300003, instance: 'f3', confName: 'K_CONF_DB_NAME', confValue: 'karbon_ss_v2', updatedAt: new Date(), user: 'laofa'},
      {key: 300004, instance: 'f4', confName: 'K_CONF_DB_NAME', confValue: 'karbon_ss_v2', updatedAt: new Date(), user: 'laofa'},
      {key: 300005, instance: 'uat', confName: 'K_CONF_DB_NAME', confValue: 'karbon_ss_v2', updatedAt: new Date(), user: 'laofa'},
      {key: 300006, instance: 'release', confName: 'K_CONF_DB_NAME', confValue: 'karbon_ss_v2', updatedAt: new Date(), user: 'laofa'},
    ],
  },
  {
    key: 4,
    confName: 'DEBUG',
    confType: 2,
    createdAt: new Date(),
    user: 'laofa',
    instances: [
      {key: 400001, instance: 'f1', confName: 'DEBUG', confValue: 'True', updatedAt: new Date(), user: 'laofa'},
      {key: 400002, instance: 'f2', confName: 'DEBUG', confValue: 'True', updatedAt: new Date(), user: 'laofa'},
      {key: 400004, instance: 'f3', confName: 'DEBUG', confValue: 'True', updatedAt: new Date(), user: 'laofa'},
      {key: 400004, instance: 'f4', confName: 'DEBUG', confValue: 'True', updatedAt: new Date(), user: 'laofa'},
      {key: 400005, instance: 'release', confName: 'DEBUG', confValue: 'True', updatedAt: new Date(), user: 'laofa'},
      {key: 400006, instance: 'uat', confName: 'DEBUG', confValue: 'True', updatedAt: new Date(), user: 'laofa'},
    ],
  },
  {
    key: 5,
    confName: 'SECRETE_KEY',
    confType: 2,
    createdAt: new Date(),
    user: 'laofa',
    instances: [
      {key: 500001, instance: 'f1', confName: 'SECRETE_KEY', confValue: 'q*q*4lpq62lfv77d1v+i%b!r6j0o2sj6+j$wv@53$z3nrd&29#', updatedAt: new Date(), user: 'laofa'},
      {key: 500002, instance: 'f2', confName: 'SECRETE_KEY', confValue: 'q*q*4lpq62lfv77d1v+i%b!r6j0o2sj6+j$wv@53$z3nrd&29#', updatedAt: new Date(), user: 'laofa'},
      {key: 500003, instance: 'f3', confName: 'SECRETE_KEY', confValue: 'q*q*4lpq62lfv77d1v+i%b!r6j0o2sj6+j$wv@53$z3nrd&29#', updatedAt: new Date(), user: 'laofa'},
      {key: 500004, instance: 'f4', confName: 'SECRETE_KEY', confValue: 'q*q*4lpq62lfv77d1v+i%b!r6j0o2sj6+j$wv@53$z3nrd&29#', updatedAt: new Date(), user: 'laofa'},
      {key: 500005, instance: 'uat', confName: 'SECRETE_KEY', confValue: 'q*q*4lpq62lfv77d1v+i%b!r6j0o2sj6+j$wv@53$z3nrd&29#', updatedAt: new Date(), user: 'laofa'},
      {key: 500006, instance: 'release', confName: 'SECRETE_KEY', confValue: 'q*q*4lpq62lfv77d1v+i%b!r6j0o2sj6+j$wv@53$z3nrd&29#', updatedAt: new Date(), user: 'laofa'},
      ],
  },
  {
    key: 6,
    confName: 'LOGGING_CONFIG',
    confType: 2,
    createdAt: new Date(),
    user: 'laofa',
    instances: [
      {key: 600001, instance: 'f1', confName: 'LOGGING_CONFIG', confValue: 'None', updatedAt: new Date(), user: 'laofa'},
      {key: 600002, instance: 'f2', confName: 'LOGGING_CONFIG', confValue: 'None', updatedAt: new Date(), user: 'laofa'},
      {key: 600003, instance: 'f3', confName: 'LOGGING_CONFIG', confValue: 'None', updatedAt: new Date(), user: 'laofa'},
      {key: 600004, instance: 'f4', confName: 'LOGGING_CONFIG', confValue: 'None', updatedAt: new Date(), user: 'laofa'},
      {key: 600005, instance: 'uat', confName: 'LOGGING_CONFIG', confValue: 'None', updatedAt: new Date(), user: 'laofa'},
      {key: 600006, instance: 'release', confName: 'LOGGING_CONFIG', confValue: 'None', updatedAt: new Date(), user: 'laofa'},
    ],
  },
];

let kTemplateSource: string = `
MEDIA_URL = '%s/media/' % K_SITE_URL
MEDIA_ROOT = '%s/karbon_media/private/karboncard_backend_media/' % K_WORK_ROOT
M2P_API_URL = 'https://ssltest.yappay.in/'  # Please add '/' at the end

ALLOWED_HOSTS = ['*']
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'HOST': K_DB_HOST,
        'PORT': K_DB_PORT,
        'NAME': K_DB_NAME,
        'USER': K_DB_USER,
        'PASSWORD': K_DB_PASSWORD,
        'CONN_MAX_AGE': None
    }
}
CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://%s:%s/%s' % (K_REDIS_HOST, K_REDIS_PORT, K_REDIS_DB_CACHE),
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
            'IGNORE_EXCEPTIONS': True,
            'PASSWORD': K_REDIS_PASSWORD,
        }
    }
}
M2P_CUSTOMER_PARAMS = {
    'Federal Bank': {
        'domain': 'https://ssltest.yappay.in/',
        'headers':
            {'Tenant': 'FBECARDS', 'Content-Type': 'application/json'},
        'business_type': 'FBECARDS',
        'business': 'FBECARDS',
        'set_pin_key': '89555EED0B07495D00A6C11789D40E1D'
    },
    'SBM': {
        'domain': 'https://ssltest.yappay.in/',
        'headers': {'Tenant': 'SBKARBON', 'Content-Type': 'application/json'},
        'business_type': 'SBKARBON',
        'business': 'SBKARBON',
        'set_pin_key': 'B244A1DCB801553825C9042A12C735DF'
    },
}
SECURITY_REMOTE_PUB_KEY_FILE = '%s/karbon_keys/m2psolutions_pub.der' % K_WORK_ROOT
SECURITY_PRIVATE_KEY_FILE = '%s/karbon_keys/karboncard.com.pkcs8' % K_WORK_ROOT

COUNT_EMAIL_ACCOUNT = [
    '184878242@qq.com', 'lhktom@gmail.com',
]

FINBIT_API_URL = 'https://trial.fin360.in'
FINBIT_LOGIN_CREDENTIAL = {'emailAddress': 'xxxx@karboncard.com', 'password': 'C@r#!82Vr$ykD'}

M2P_API_KYC_URL = 'https://kycuat.yappay.in/'

M2P_KYC_PARAMS = {
    'Federal Bank': {
        'domain': 'https://kycuat.yappay.in/',
        'headers':
            {'partnerId': 'FBECARDS', 'partnerToken': 'Basic RkJFQ0FSRFM='},
        'business_type': 'FBECARDS',
        'business': 'FBECARDS',

    },
    'SBM': {
        'domain': 'https://kycuat.yappay.in/',
        'headers': {'partnerId': 'SBKARBON', 'partnerToken': 'Basic U0JLQVJCT04='},
        'business_type': 'SBKARBON',
        'business': 'SBKARBON',
    },
}
logging.config.dictConfig({
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'console': {
            'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
        },
        'django.server': DEFAULT_LOGGING['formatters']['django.server'],

    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'console',
        },
        'django.server': DEFAULT_LOGGING['handlers']['django.server'],

    },
    'loggers': {
        '': {
            'level': 'INFO',
            'handlers': ['console',
                         ], },
        'project': {'level': LOGLEVEL,
                    'handlers': ['console', ],
                    # required to avoid double logging with root logger
                    'propagate': False, },
        'django.server': DEFAULT_LOGGING['loggers']['django.server'],
    }

})
M2P_KYC_FILE_BASE_AUTH = {
    'partnerId': 'FBECARDS',
    'partnerToken': 'Basic RkJFQ0FSRFM='
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=500),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': True,

    'ALGORITHM': 'HS256',
    # 'SIGNING_KEY': settings.SECRET_KEY,
    'VERIFYING_KEY': None,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'USER_ID_FIELD': 'uuid',
    'USER_ID_CLAIM': 'user_uuid',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}

YODLEE_PRIVATE_KEY = '%s/karbon_keys/yodlee.pk' % K_WORK_ROOT
YODLEE_URL = 'https://usyi.stage.api.yodlee.com/ysl/'

ISSUE_ID = 'ead31fa0-75b1-43f8-bc58-8996a2728229'
REWARDS_EMAIL_ADDRESS = {
    'AWS': {'to_email': None, 'cc': ['tom@karboncard.com']},
    'Amazon': {'to_email': None, 'cc': ['tom@karboncard.com']},
    'WeWork': {'to_email': None, 'cc': ['tom@karboncard.com']},
    'Uber': {'to_email': None, 'cc': ['tom@karboncard.com']},
    'Flipkart': {'to_email': None, 'cc': ['tom@karboncard.com']},
    'MakeMyTrip': {'to_email': None, 'cc': ['tom@karboncard.com']},
}

EXT_AUTH_MODE = True

# TODO NEW ADD REDIS SAVE OYO CODE LENGTH
REDIS_OYO_CODE_LENGTH = 200
OYO_REPEAT_CODE_FILE_PATH = '%s/karbon_backend_data_import/K23C.csv' % K_WORK_ROOT
OYO_NEW_CODE_FILE_PATH = '%s/karbon_backend_data_import/K45C.csv' % K_WORK_ROOT

PUBLIC_MEDIA_ROOT = '%s/karbon_media/public/kbbackpubmedia/' % K_WORK_ROOT
PUBLIC_MEDIA_URL = '%s/kbbackpubmedia/' % K_SITE_URL

VENTURE_CAPITAL_FRONTEND_URL = 'https://vc.yorecard.com/'

# celery config
BROKER_URL = 'redis://:hk110@10.110.0.13:6385/2' % (K_REDIS_PASSWORD, K_REDIS_HOST, K_REDIS_PORT, K_REDIS_DB_CELERY)
CELERY_RESULT_BACKEND = 'django-db'
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'
# DJANGO_CELERY_BEAT_TZ_AWARE = False
DJANGO_CELERY_RESULTS_TASK_ID_MAX_LENGTH = 191
DJANGO_CELERY_RESULTS = {'ALLOW_EDITS': False}
STATEMENT_TIMEZONE = 'Asia/Kolkata'

VC_CONNECT_PERMISSION = {
    # allow time
    'LIFETIME': 60 * 30,
    #
    'AUTH_HEADER': 'VCCONNECT',
}

M2P_VIRTUAL_ACCOUNT_PREFIX = 'XXXX'

ADMIN_PORTAL_DOWNLOAD_URL = '%s/' % K_ADMIN_PORTAL_URL

# paytm ock time
PAYTM_LOCK_TIME = 15 * 60

# TODO Security file download params
SECURITY_FILE_DOWNLOAD = {
    'key': 'xv4eiwL1EJhFF1wq1dE23oaHK65pveGm',
    'iv': 'PbYDJQ1HhbeGiEwS'
}
PAYTM_URL = 'https://securegw-stage.paytm.in/'
PAYTM_CHECK_URL = 'https://securegw-stage.paytm.in/order/status'
PAYTM_FIX_PARAMETERS = {
    'MID': 'Karbon20775539448833',
    'WEBSITE': 'WEBSTAGING',
    'INDUSTRY_TYPE_ID': 'Retail',
    'PAYMENT_MODE_ONLY': 'YES',
    'AUTH_MODE': 'USRPWD',
    'PAYMENT_TYPE_ID': 'NB',
}
PAYTM_KEY = 'KV24F6nWUreM3O9G'
PAYTM_LOCK_TIME = 2
# New added on 2019-11-13 end
OTP_INTERNAL = 2 * 60
OTP_PERIOD = 15 * 60

ALLOW_UPLOAD_FILE_TYPE = ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx', 'xls', 'xlsx']
DOWNLOAD_FILE_URL_INTERVAL = 5 * 60

ALLOW_UPLOAD_IMAGE_TYPE = ['jpg', 'jpeg', 'png']

MSG91_SETTINGS = {
    'COMMON': {
        'BASE_URL': 'https://api.msg91.com',
        'AUTH_KEY': '302267AdEtq8hwsJ5dc13a18',
    },
    'SEND_OTP': {
        'OTP_LENGTH': '4',
        'API_VERSION': '5',
        'OTP_EXPIRY': str(24 * 60),  # in minutes, default 1 day aka 24 * 60
        'TEMPLATES': {'default': '5ddf9b6cd6fc057b64474fa3'},
    },
    'SEND_SMS': {'API_VERSION': '2', 'SENDER': {'default': 'KARBON'}},
}

MSG91_SEND_OTP_TEMPLATES = MSG91_SETTINGS['SEND_OTP']['TEMPLATES']

FAILED_TXN_EMAIL = {
    'subject': 'Failed Transaction <time: {now} IST>',
    'template': 'mail/transactions/failed_transaction.html',
    'receiver': ['test@karboncard.com'],
}
CARD_APPLICATION_NOTICE_OPS = {
    'receiver': 'test@karboncard.com',
    'cc': ['test@karboncard.com'],
}

SYNC_REPAYMENT_SCHEDULE = timedelta(minutes=1)
REPAYMENT_EMAIL_COUNT_POINT = (
    timedelta(minutes=3) / SYNC_REPAYMENT_SCHEDULE,
    timedelta(minutes=5) / SYNC_REPAYMENT_SCHEDULE,
)

NOTIFY_INCOMPLETE_SCHEDULE = timedelta(hours=1)
NOTIFY_INCOMPLETE_TIME = timedelta(hours=12)
NOTIFY_NO_TRANSACTION_SCHEDULE = timedelta(days=1)
SKIP_STATEMENT_UPLOAD = True

SALES_EMAIL = 'test@karboncard.com'
MASTER_ACCOUNT_ALERT_TO = [
    'test@karboncard.com',
]
MASTER_ACCOUNT_ALERT_CC = [
    'test@karboncard.com',
]
ECOLLECT = {
    'YESBANK': {
        'CUSTOMER_CODE': 'KRBN00',
        'CREDENTIALS': {
            'username': 'yesbank',
            'password': 'pass123'
        }
    }
}

OWNER_VERIFY_EMAIL_NOTIFY_OPS = ['sales@karboncard.com'] if not DEBUG else ['test@karboncard.com']

SEVEN_DAYS_INCOMPLETE = timedelta(days=7) if not DEBUG else timedelta(minutes=1)
FOURTEEN_DAYS_INCOMPLETE = timedelta(days=14) if not DEBUG else timedelta(minutes=2)

YELLOWER_MESSAGER_TOKEN = '401f7ac837da42b97f613d789819ff93537bee6a'

DIGIO_NACH_API_CONF = {
    'client_id': 'AI81FNNISVQW6ALCA3IUTJZRUZOV1AIL',
    'client_secret': 'KRJDPGYQ279ZCS2T9YOULDXCCMK1QSUD',
    'base_url': 'https://ext.digio.in:444',
}

NACH_CONF = {
    'corporate_account_number': '002281300008252',
}
BILLDESK_CONFIG = {
    'merchant_id': 'BDSKUATY',
    'product_id': 'DIRECT',
    'checksum_key': 'G3eAmyVkAzKp8jFq0fqPEqxF4agynvtJ',
    'security_id': 'bdskuaty',
    'submit': 'https://uat.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=PGIME1000&hidOperation=ME100',
    'query': 'https://uat.billdesk.com/pgidsk/PGIQueryController',
}

KUDOS_LOANREQ_API_CONF = {
    'base_url': 'http://sandbox.kudosfinance.in:5000',
    'company_code': 'INT0083',
    'access_token': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb21wYW55X2lkIjo5MiwiY29tcGFueV9jb2RlIjoiSU5UMDA4MyIsInByb2R1Y3RfaWQiOjEyNSwibG9hbl9zY2hlbWFfaWQiOiIxNDQiLCJjcmVkaXRfcnVsZV9ncmlkX2lkIjpudWxsLCJhdXRvbWF0aWNfY2hlY2tfY3JlZGl0IjowLCJ0eXBlIjoiYXBpIiwidG9rZW5faWQiOiI5Mi0xMjUtMTU5MTY4MzAzODA2MiIsImVudmlyb25tZW50Ijoic2FuZGJveCIsImlhdCI6MTU5MTY4MzAzOH0.64cVmTHcSM-SfKjyjtRcSij-6QK1fwQWtdokO-vaIdk',
}
KUDOS_BENEFICIARY_ACCOUNT = {
    'borro_bank_name': 'SBM',
    'borro_bank_acc_num': '20062020000273',
    'borro_bank_ifsc': 'STCB0000065',
}

TESTING_EMAIL = 'karbontest@163.com'
TESTING_SMS = '6363642420'
TESTING_WHATSAPP = '6363642420'

SBM_SFTP_ACCESS = {
    'host_name': '54.222.217.222',
    'user_name': 'tom',
    'password': 'tom_Karbon_35464_sjs_K89',
    'root_dir': K_SFTP_SUB_DIR
}

PAYOUT = {
    'YESBANK': {
        'base_url': 'https://uatsky.yesbank.in/app/uat/',
        'x-ibm-client-secret': 'A8cT5kG0hF3hS6yQ1tF5fW7mI3lB7cI1pT5qA8wX8iG8lK7gK2',
        'x-ibm-client-id': '1e77ab38-4e29-4f85-be98-c72dd9a3340e',
        'username': 'testclient',
        'password': 'OxYcool@123',
        'accept': 'application/json',
        'ConsentId': '453733',
        'Identification': '000190600017042',
        'SecondaryIdentification': '453733',
        'verify': '%s/karbon_keys/yesbank/sky_yesbank_all.txt' % K_WORK_ROOT,
        'cert': (
            '%s/karbon_keys/karboncard/godaddy_karboncard_all.crt' % K_WORK_ROOT,
            '%s/karbon_keys/karboncard/karboncard.key' % K_WORK_ROOT,
        ),
    }
}
`;


const errorReturn =  {
  statusCode: 401,
  data: {message: 'authorize fail'},
}

function checkTokenFail(req: Request) {
  if (req.header('authorization') &&
    req.header('authorization') === 'xxxxxxxxxxjkajdja988uwuruw&8qq9wr989234202342402') {
    return false;
  }
  return true;
}

function getItemConfig(req: Request, res: Response, u: string) {
  if (checkTokenFail(req)) {
    res.status(errorReturn.statusCode);
    return res.json({message: errorReturn.data});
  }

  let realUrl = u;
  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }

  const params = (parse(realUrl, true).query as unknown) as TableListParams;
  // after params the confType's type is still string, need to convert to number
  if (params.confType) {
    params.confType = +params.confType;
  }

  let dataSource = [ ...kConfigPrimarySource ];

  if (params.confName) {
    dataSource = dataSource.filter((data) => data.confName.includes(params.confName || ''));
  }
  if (params.confType) {
    dataSource = dataSource.filter((data) => data.confType === params.confType);
  }

  const result = {
    data: dataSource,
    success: true,
  };
  console.log(result);
  return res.json(result);
}


function getTemplateConfig(req: Request, res: Response) {
  if (checkTokenFail(req)) {
    res.status(errorReturn.statusCode);
    return res.json({message: errorReturn.data});
  }

  if (req.header('authorization') && req.header('authorization') === 'xxxxxxxxxxjkajdja988uwuruw&8qq9wr989234202342402') {
    const result = {
      data: kTemplateSource,
    };
    return res.json(result);
  } else {
    const result = {
      data: errorReturn.data,
    };
    res.status(errorReturn.statusCode);
    return res.json(result);
  }
}

function postItemConfig(req: Request, res: Response, u: string, b: Request) {
  if (checkTokenFail(req)) {
    res.status(errorReturn.statusCode);
    return res.json({message: errorReturn.data});
  }

  let realUrl = u;
  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }

  const body = (b && b.body) || req.body;
  const { method, key, confName, confValue} = body;
  switch (method) {
    /* eslint no-case-declarations:0 */
    case 'delete':
      kConfigPrimarySource = kConfigPrimarySource.filter((item) => key !== item.key);
      break;
    case 'post':
      (() => {
        const newConfig: KConfigItem = {
          key: kConfigPrimarySource.length + 1,
          confName: confName,
          confType: confName.startsWith("K_CONF_")? 1: 2,
          createdAt: new Date(),
          user: 'laofa',
          instances: [
            {key: kConfigPrimarySource.length * 100000 + 1,
              instance: "f1", confName: confName, confValue: confValue, updatedAt: new Date(), user: "lafoa"},
            {key: kConfigPrimarySource.length * 100000 + 2,
              instance: "f2", confName: confName, confValue: confValue, updatedAt: new Date(), user: "lafoa"},
            {key: kConfigPrimarySource.length * 100000 + 3,
              instance: "f3", confName: confName, confValue: confValue, updatedAt: new Date(), user: "lafoa"},
            {key: kConfigPrimarySource.length * 100000 + 4,
              instance: "f4", confName: confName, confValue: confValue, updatedAt: new Date(), user: "lafoa"},
            {key: kConfigPrimarySource.length * 100000 + 5,
              instance: "uat", confName: confName, confValue: confValue, updatedAt: new Date(), user: "lafoa"},
            {key: kConfigPrimarySource.length * 100000 + 6,
              instance: "release", confName: confName, confValue: confValue, updatedAt: new Date(), user: "lafoa"},
          ],
        };
        kConfigPrimarySource.unshift(newConfig);
        return res.json(newConfig);
      })();
      return;
    case 'update':
      (() => {
        let newConfig = {};
        kConfigPrimarySource = kConfigPrimarySource.map((item) => {
          if (item.confName === confName) {
            item.instances = item.instances.map((inneritem) => {
              if (inneritem.key === key) {
                const updatedAt = new Date();
                // it's async, so can't only return inneritem.
                return {...inneritem, confValue, updatedAt};
              }
              return inneritem;
            });
          }
          return item;
        });

        return res.json(newConfig);
      })();
      return;
    default:
      break;
  }
  const result = {
    list: kConfigPrimarySource,
  };
  return res.json(result);
}


function postTemplateConfig(req: Request, res: Response, u: string, b: Request) {
  if (checkTokenFail(req)) {
    res.status(errorReturn.statusCode);
    return res.json({message: errorReturn.data});
  }

  let realUrl = u;
  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }

  const body = (b && b.body) || req.body;
  const { content } = body;
  kTemplateSource = content;
  const result = {
    content: content,
  };
  return res.json(result);
}


/*
export default {
  'GET /api/v1/kconfig/items': getItemConfig,
  'POST /api/v1/kconfig/items': postItemConfig,
  'GET /api/v1/kconfig/template': getTemplateConfig,
  'POST /api/v1/kconfig/template': postTemplateConfig,
};
*/
